var rootPath = '';//kk.getRootPath();

/* contentCatDom */
var contentCatDom = '\
<form class="form-horizontal" id="contentCatForm">\
	<div class="form-group">\
		<label for="name" class="col-sm-2 control-label">名称</label>\
		<div class="col-sm-10">\
			<input type="text" class="form-control" id="name" name="name" placeholder="名称">\
		</div>\
	</div>\
	<div class="form-group">\
		<label for="pidName" class="col-sm-2 control-label">父节点</label>\
		<div class="col-sm-10">\
			<div class="input-group">\
				<input type="hidden" id="pid" name="pid">\
			    <input type="text" class="form-control" id="pidName" name="pidName" disabled>\
				<span class="input-group-btn">\
					<button type="button" class="btn btn-info btn-flat" onclick="showMenu();">选择</button>\
				</span>\
			</div>\
			<div id="menuContent" class="menuContent" style="display:none; position:absolute; background-color: #f4f4f4; z-index: 4002;">\
				<ul id="parentTree" class="ztree"></ul>\
			</div>\
		</div>\
	</div>\
	<div>\
		<input type="hidden" name="id" />\
	</div>\
</form>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
var validator = null;
function CRUDContentCatFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Setting/ContentCat/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Setting/ContentCat/delete?id=' + id;
		kk.deleteObj(url, xtt);
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
	
	var validator;
	
	xpopup.window({
	    width: 800,
	    height: 400,
		title: '编辑',		// 因为afterShow中已经有新建和查看了
	    content: contentCatDom,
        buttons: [{
        	id:	'btnOk',
            text: '确定',
            'class': 'btn btn-info btn-flat',
            handler: function ($this) {
    	 		if (validator.form() && doCU(operCode, id, index)) {
            		$this.destroy();
    	 		}
            }
        }, {
        	id:	'btnCancel',
            text: '取消',
            'class': 'btn btn-default btn-flat',
            handler: function ($this) {
        		$this.destroy();
            }
        }],
        afterShow: function ($this) {	        	
			if (operCode == CREATE) {
				$this.setTitle('添加');

				initTree();
			} else if (operCode == READ) {
				$this.setTitle('查看');
				$('#btnOk').hide();
	    		$('#btnCancel').text('关闭');

				$('#contentCatForm').setForm(obj);
				initTree(obj.id, obj.pid);
				
				$('#contentCatForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
			} else if (operCode == UPDATE) {					
				$this.setTitle('编辑');

				$('#contentCatForm').setForm(obj);
				initTree(obj.id, obj.pid);
			}
    		
        	validator = $("#contentCatForm").validate({
    			onfocusout: function(element) {
    				$(element).valid();
    			},
                rules: {
        			name: "required",
        			pid: "required",
                },
                messages: {
        			name: "请输入名称",
        			pid: "请输入pid",
                }
            });
        }
	});
}

/* Create & Update */
/* CATEGORY TYPE 1: LIST, 2: SINGLE, 3: LINK */
var COLUMN = 1, LIST = 2, SINGLE = 3, LINK = 4;
function doCU(operCode, id, index) {
    var url;
    var method;
    var jsonObj = $('#contentCatForm').serializeObject();
	var jsonStr = JSON.stringify(jsonObj);
//console.log('jsonStr = ' + jsonStr);
	var result;
	
	if (operCode == CREATE) {
	 	url = rootPath + '/Setting/ContentCat/save';
		method = "POST";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	} else if (operCode == UPDATE) {
	 	url = rootPath + '/Setting/ContentCat/update?id=' + id;
		method = "PUT";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	}
	
	return false;
}


/***** TREE ******/
/* initTree() */
function initTree(id, pid) {
	pid = pid === undefined ? 0 : pid;					// pid <==> 0
	
	var setting = {
		async: {
			enable: true,
			type: "get",
			url: rootPath + '/Setting/ContentCat/getAll',
			autoParam: ["id", "name"],
			dataFilter: ajaxDataFilter
		},
		callback: {
			onClick: onClick,
			onAsyncSuccess: zTreeOnAsyncSuccess
		}, 
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",
				rootPId: 0
			},
			key: {
	            url: "xUrl"
	        }
		}
	};
	
	function ajaxDataFilter(treeId, parentNode, responseData) {
		var newData = new Array();
		var rootData = {
			id: 0,
			pid: -1,
			name: '根元素'
		};
		newData.push(rootData);
		
		var data = responseData.obj;
		for (var i = 0; i < data.length; i++) {
			if (data[i].id != id && data[i].pid != id) {
				newData.push(data[i]);
			}
		}
		
	    return newData;
	}
	
	function onClick(e, treeId, treeNode) {
		$('#pidName').val(treeNode.name);
		$('#pid').val(treeNode.id);
		return false;
	}
	
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {		// 加载成功后赋值
		var node = zTreeObj.getNodeByParam("id", pid);
		$('#pidName').val(node.name);
	}

	zTreeObj = $.fn.zTree.init($("#parentTree"), setting);
}
